import { createRouter, createWebHistory } from 'vue-router'
import pinia from '../stores'
import { useUserStore } from '@/stores/UserStore'
import Home from '../views/Home.vue'
import Login from '../views/login.vue'


const userStore = useUserStore(pinia)

const routes = [
  { 
    path: '/', 
    component: Login,
    meta: { requiresAuth: false }
  },
  { 
    path: '/login', 
    component: Login,
    meta: { requiresAuth: false }
  },
  { 
    path: '/home', 
    component: Home,
    meta: { requiresAuth: true }
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

//路由守卫
router.beforeEach((to, from, next) => {
  if (!userStore.userInfo) {
    userStore.initializeFromStorage()
  }
  
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    next({ path: '/login' })
  } else if (to.path === '/login' && userStore.isLoggedIn) {
    next()
  } else {
    next()
  }
})

export default router